"""
性能优化缓存模块
提供内存缓存和文件缓存功能
"""

import hashlib
import pickle
import time
from pathlib import Path
from typing import Any, Optional, Dict
import logging

class PerformanceCache:
    """性能优化缓存系统"""
    
    def __init__(self, config: Dict[str, Any]):
        """初始化缓存系统"""
        self.config = config
        self.logger = logging.getLogger('image_cropping_system')
        
        # 内存缓存
        self.memory_cache: Dict[str, Dict[str, Any]] = {}
        self.max_memory_size = config.get('cache', {}).get('max_size', 100)
        self.ttl = config.get('cache', {}).get('ttl', 3600)
        
        # 文件缓存
        self.cache_dir = Path('cache')
        self.cache_dir.mkdir(exist_ok=True)
        
        self.logger.info(f"缓存系统初始化完成，内存缓存大小: {self.max_memory_size}, TTL: {self.ttl}秒")
    
    def _generate_key(self, data: Any) -> str:
        """生成缓存键"""
        if isinstance(data, str):
            content = data
        elif isinstance(data, dict):
            content = str(sorted(data.items()))
        else:
            content = str(data)
        
        return hashlib.md5(content.encode()).hexdigest()
    
    def get(self, key: Any) -> Optional[Any]:
        """获取缓存值"""
        cache_key = self._generate_key(key)
        
        # 检查内存缓存
        if cache_key in self.memory_cache:
            cache_item = self.memory_cache[cache_key]
            if time.time() - cache_item['timestamp'] < self.ttl:
                self.logger.debug(f"内存缓存命中: {cache_key}")
                return cache_item['value']
            else:
                # 过期，删除
                del self.memory_cache[cache_key]
        
        # 检查文件缓存
        cache_file = self.cache_dir / f"{cache_key}.cache"
        if cache_file.exists():
            try:
                with open(cache_file, 'rb') as f:
                    cache_item = pickle.load(f)
                
                if time.time() - cache_item['timestamp'] < self.ttl:
                    # 加载到内存缓存
                    self.memory_cache[cache_key] = cache_item
                    self.logger.debug(f"文件缓存命中: {cache_key}")
                    return cache_item['value']
                else:
                    # 过期，删除文件
                    cache_file.unlink()
            except Exception as e:
                self.logger.warning(f"读取缓存文件失败: {e}")
        
        return None
    
    def set(self, key: Any, value: Any) -> None:
        """设置缓存值"""
        cache_key = self._generate_key(key)
        cache_item = {
            'value': value,
            'timestamp': time.time()
        }
        
        # 内存缓存
        if len(self.memory_cache) >= self.max_memory_size:
            # 删除最旧的缓存项
            oldest_key = min(self.memory_cache.keys(), 
                           key=lambda k: self.memory_cache[k]['timestamp'])
            del self.memory_cache[oldest_key]
        
        self.memory_cache[cache_key] = cache_item
        
        # 文件缓存（异步保存）
        try:
            cache_file = self.cache_dir / f"{cache_key}.cache"
            with open(cache_file, 'wb') as f:
                pickle.dump(cache_item, f)
        except Exception as e:
            self.logger.warning(f"保存缓存文件失败: {e}")
    
    def clear(self) -> None:
        """清空所有缓存"""
        self.memory_cache.clear()
        
        # 清空文件缓存
        for cache_file in self.cache_dir.glob("*.cache"):
            try:
                cache_file.unlink()
            except Exception as e:
                self.logger.warning(f"删除缓存文件失败: {e}")
        
        self.logger.info("缓存已清空")
    
    def get_stats(self) -> Dict[str, Any]:
        """获取缓存统计信息"""
        memory_size = len(self.memory_cache)
        file_count = len(list(self.cache_dir.glob("*.cache")))
        
        return {
            'memory_cache_size': memory_size,
            'file_cache_count': file_count,
            'max_memory_size': self.max_memory_size,
            'ttl': self.ttl
        }